<!-- <template>
  <div>
    <p v-highlight>这是一段需要高亮的文本。</p>
  </div>
</template>

<script>
export default {
  directives: {
    highlight: {
      bind(el) {
        el.addEventListener('mouseup', () => {
          const selection = window.getSelection().toString();
          if (selection) {
            const span = document.createElement('span');
            span.style.backgroundColor = 'yellow';
            const range = window.getSelection().getRangeAt(0);
            range.surroundContents(span);
          }
        });
      },
    },
  },
};
</script> -->

<template>
  <div>
    <div v-html="abc"></div>
    <textarea ref="textarea" @mouseup="highlightSelectedText"></textarea>
  </div>
</template>

<script>
export default {
  data() {
    return {
      abc: '<span><mark>abc</mark>123</span>',
      textareaValue: '',
    }
  },
  methods: {
    highlightSelectedText() {
      const textarea = this.$refs.textarea;
      const selection = window.getSelection().toString(); // 获取选择的文本

      if (selection) {
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;

        const highlightedText = `<mark>${selection}</mark>`; // 使用 <mark> 标签包裹选中的文本
        const newText = this.textareaValue.slice(0, start) + highlightedText + this.textareaValue.slice(end);

        this.textareaValue = newText; // 更新 textarea 的值
      }
    },
  },
};
</script>